package com.test.controller;


import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.jhlabs.image.WoodFilter;


/**
 * SpringSide Base Controller鐨勫熀绫�
 */
abstract public class BaseController extends MultiActionController {


    /** json日期格式处理 */
    protected static SerializeConfig mapping = new SerializeConfig();

    private static String dateFormat;
    static {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
        mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
    }

   
    public void export(List<String> titles, List<List<String>> lines,String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception {
    	 if (titles == null) {
             throw new Exception("导出表头不能为空");
         }
         if (lines != null && lines.get(0).size() != titles.size()) {
             throw new Exception("表头和行数据不对称");
         }
         response.setContentType("application/vnd.ms-excel");
         OutputStream out = null;
    	 final String userAgent = request.getHeader("USER-AGENT");
         try {
             String finalFileName = null;
             if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
                 finalFileName = new String(fileName.getBytes(), "ISO8859-1");
             } else {// IE浏览器(头名称叫:MSIE)和其他浏览器
                 finalFileName = URLEncoder.encode(fileName, "UTF8");
             }
             response.setHeader("Content-Disposition", "attachment; filename=" + finalFileName + ".xlsx");
             out = response.getOutputStream();
           //创建Excel工作簿
             XSSFWorkbook workbook = new XSSFWorkbook();
             Sheet sheet = workbook.createSheet();
             Row row = sheet.createRow(0);
             Cell cell = null;
             for(int i=0;i<titles.size();i++){
            	 cell = row.createCell(i);
                 cell.setCellValue(titles.get(i));
             }
           //追加数据
             for(int i=1;i<=lines.size();i++){
                 Row nextRow = sheet.createRow(i);
                 for(int j=0;j<lines.get(i-1).size();j++){
                     Cell cell2 = nextRow.createCell(j);
                     cell2.setCellValue(lines.get(i-1).get(j));
                 }
             }
           workbook.write(out);
//           workbook.close();//????
         } catch (Exception e) {
             // e.printStackTrace();
         }finally{
        	 out.flush();
        	 out.close();
        	 
         }
         
       
    }
  
    
  

    /**
     * 鐩存帴鍚戝鎴风杩斿洖Content瀛楃涓诧紝涓嶇敤閫氳繃View椤甸潰娓叉煋.
     */
    protected void rendText(HttpServletResponse response, Object content) throws IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        if (null == content) {
            content = "";
        }
        PrintWriter out = response.getWriter();
        out.write(content.toString());
        out.flush();
        out.close();
    }

    /**
     * 鍚慥iew灞備紶閫抦essage鏃跺皢message鏀惧叆httpSession鐨刴essages鍙橀噺涓� 鏀惧湪session涓兘淇濊瘉message鍗充娇Redirect涔熶笉浼氭秷澶便�闇�厤鍚�
     * {@link  }浣跨敤
     */
    @SuppressWarnings("unchecked")
    protected void saveMessage(HttpServletRequest request, String message) {
        if (StringUtils.isNotBlank(message)) {
            List<String> messages = (List<String>) WebUtils.getOrCreateSessionAttribute(request.getSession(),
                    "messages", ArrayList.class);
            messages.add(message);
        }
    }

    /**
     * 瀛愮被瀹炵幇锛岄〉闈㈠垵濮嬪寲鍙傛暟
     * 
     * @param model
     * @throws Exception
     */
    protected void initData(Map<String, Object> model) throws Exception {
    }
}
